<template>
  <div class="activity-container">
    <div class="activity-header">
      <div class="activity-title">
        <el-icon><Notification /></el-icon>
        <span>活动公告</span>
      </div>
      <el-button type="primary" icon="Plus" @click="open = true" size="large" class="add-btn">新增活动</el-button>
    </div>
    <el-row :gutter="24" class="activity-list">
      <el-col :span="8" v-for="item in activityList" :key="item.id">
        <el-card class="activity-card" shadow="hover">
          <div class="card-image">
            <el-image :src="item.imageUrl" fit="cover" class="card-img" v-if="item.imageUrl" />
            <div class="no-img" v-else><el-icon><Picture /></el-icon></div>
          </div>
          <div class="card-content">
            <div class="card-title">{{ item.title }}</div>
            <div class="card-time">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatTime(item.startTime) }} ~ {{ formatTime(item.endTime) }}</span>
            </div>
            <div class="card-desc">{{ item.description }}</div>
          </div>
        </el-card>
      </el-col>
      <el-empty v-if="activityList.length === 0" description="暂无活动公告" />
    </el-row>

    <!-- 新增活动弹窗 -->
    <el-dialog v-model="open" title="发布新活动" width="800px" :close-on-click-modal="false" class="publish-dialog">
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="110px" class="publish-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入活动标题" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="isPlatform">
              <el-radio-group v-model="form.isPlatform">
                <el-radio :label="false">商家活动</el-radio>
                <el-radio :label="true">平台活动</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="活动时间" prop="timeRange">
              <el-date-picker
                v-model="form.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动图片" prop="imageUrl">
              <el-upload
                class="avatar-uploader"
                :action="uploadFileUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入活动描述" maxlength="200" show-word-limit />
        </el-form-item>
        <!-- 商品信息 -->
        <el-form-item label="活动商品" required>
          <div class="product-list">
            <el-card v-for="(product, idx) in form.products" :key="idx" class="product-card" shadow="never">
              <el-row :gutter="12">
                <el-col :span="6">
                  <el-input v-model="product.productName" placeholder="商品名称" maxlength="30" />
                </el-col>
                <el-col :span="6">
                  <el-input v-model="product.description" placeholder="商品描述" maxlength="50" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model.number="product.originalPrice" placeholder="原价" type="number" min="0" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model.number="product.activityPrice" placeholder="活动价" type="number" min="0" />
                </el-col>
                <el-col :span="2">
                  <el-input v-model.number="product.totalStock" placeholder="库存" type="number" min="1" />
                </el-col>
                <el-col :span="2">
                  <el-input v-model.number="product.limitPerUser" placeholder="限购" type="number" min="1" />
                </el-col>
                <el-col :span="2">
                  <el-upload
                    :action="uploadFileUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="(res) => handleProductImageSuccess(res, idx)"
                    :before-upload="beforeImageUpload"
                  >
                    <img v-if="product.imageUrl" :src="product.imageUrl" class="product-avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-col>
                <el-col :span="2">
                  <el-button icon="Delete" type="danger" circle @click="removeProduct(idx)" v-if="form.products.length > 1" />
                </el-col>
              </el-row>
            </el-card>
            <el-button icon="Plus" type="primary" plain @click="addProduct" style="margin-top: 8px;">添加商品</el-button>
          </div>
        </el-form-item>
        <!-- 活动规则 -->
        <el-form-item label="活动规则">
          <div class="rule-list">
            <el-card v-for="(rule, idx) in form.rules" :key="idx" class="rule-card" shadow="never">
              <el-row :gutter="12">
                <el-col :span="6">
                  <el-select v-model="rule.ruleType" placeholder="规则类型" style="width: 100%">
                    <el-option label="用户等级" value="1" />
                    <el-option label="积分限制" value="2" />
                  </el-select>
                </el-col>
                <el-col :span="10">
                  <el-input v-model="rule.ruleCondition" placeholder="规则条件(JSON)" />
                </el-col>
                <el-col :span="6">
                  <el-input v-model="rule.ruleDescription" placeholder="规则描述" />
                </el-col>
                <el-col :span="2">
                  <el-button icon="Delete" type="danger" circle @click="removeRule(idx)" v-if="form.rules.length > 1" />
                </el-col>
              </el-row>
            </el-card>
            <el-button icon="Plus" type="primary" plain @click="addRule" style="margin-top: 8px;">添加规则</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting" size="large" style="width: 180px;">发布活动</el-button>
          <el-button @click="reset" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { publishActivity, getActivityList } from '@/api/activity/activity.js'
import { getToken } from '@/utils/auth'

const open = ref(false)
const submitting = ref(false)
const activityList = ref([])

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/upload')
const headers = computed(() => ({ Authorization: 'Bearer ' + getToken() }))

const form = reactive({
  title: '',
  description: '',
  imageUrl: '',
  isPlatform: false,
  timeRange: [],
  products: [
    {
      productName: '',
      description: '',
      imageUrl: '',
      originalPrice: null,
      activityPrice: null,
      totalStock: 1,
      limitPerUser: 1
    }
  ],
  rules: [
    {
      ruleType: '1',
      ruleCondition: '{"minLevel": 1}',
      ruleDescription: '用户等级需大于等于1级'
    }
  ]
})

const rules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请上传活动图片', trigger: 'change' }
  ]
}

const activityRef = ref()

function handleImageSuccess(response) {
  form.imageUrl = response.url
}
function beforeImageUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    window.$modal?.msgError('上传图片只能是 JPG/PNG/GIF 格式!')
  }
  if (!isLt2M) {
    window.$modal?.msgError('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
function handleProductImageSuccess(response, idx) {
  form.products[idx].imageUrl = response.url
}
function addProduct() {
  form.products.push({
    productName: '',
    description: '',
    imageUrl: '',
    originalPrice: null,
    activityPrice: null,
    totalStock: 1,
    limitPerUser: 1
  })
}
function removeProduct(idx) {
  if (form.products.length > 1) form.products.splice(idx, 1)
}
function addRule() {
  form.rules.push({
    ruleType: '1',
    ruleCondition: '{"minLevel": 1}',
    ruleDescription: '用户等级需大于等于1级'
  })
}
function removeRule(idx) {
  if (form.rules.length > 1) form.rules.splice(idx, 1)
}
function reset() {
  form.title = ''
  form.description = ''
  form.imageUrl = ''
  form.isPlatform = false
  form.timeRange = []
  form.products = [
    {
      productName: '',
      description: '',
      imageUrl: '',
      originalPrice: null,
      activityPrice: null,
      totalStock: 1,
      limitPerUser: 1
    }
  ]
  form.rules = [
    {
      ruleType: '1',
      ruleCondition: '{"minLevel": 1}',
      ruleDescription: '用户等级需大于等于1级'
    }
  ]
}
function submitForm() {
  activityRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    const [startTime, endTime] = form.timeRange
    const payload = {
      ...form,
      startTime,
      endTime
    }
    try {
      await publishActivity(payload, form.isPlatform)
      window.$modal?.msgSuccess('活动发布成功！')
      open.value = false
      reset()
      fetchList()
    } catch (e) {
      window.$modal?.msgError('发布失败，请重试')
    } finally {
      submitting.value = false
    }
  })
}
function formatTime(time) {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}
async function fetchList() {
  // 这里假设getActivityList返回{ rows: [...] }
  const res = await getActivityList()
  activityList.value = res.rows || []
}
onMounted(fetchList)
</script>

<style scoped>
.activity-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px 0 40px 0;
}
.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}
.activity-title {
  display: flex;
  align-items: center;
  font-size: 28px;
  font-weight: 600;
  color: #2d3a4b;
  gap: 10px;
}
.add-btn {
  font-size: 16px;
  padding: 0 32px;
  height: 44px;
  border-radius: 24px;
}
.activity-list {
  min-height: 320px;
}
.activity-card {
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 24px;
  transition: box-shadow 0.2s;
  box-shadow: 0 2px 12px 0 rgba(80,120,200,0.07);
  display: flex;
  flex-direction: column;
  height: 340px;
}
.card-image {
  width: 100%;
  height: 160px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}
.card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.no-img {
  width: 100%;
  height: 100%;
  color: #d3d3d3;
  font-size: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 18px 10px 10px 10px;
}
.card-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.card-time {
  font-size: 13px;
  color: #888;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}
.card-desc {
  font-size: 15px;
  color: #444;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.publish-dialog >>> .el-dialog__header {
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}
.publish-form {
  margin-top: 0;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  text-align: center;
  line-height: 120px;
}
.avatar {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}
.product-list {
  width: 100%;
}
.product-card {
  margin-bottom: 10px;
  background: #f9fbfd;
  border-radius: 10px;
  padding: 12px 16px 8px 16px;
}
.product-avatar {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 6px;
  background: #f5f7fa;
}
.rule-list {
  width: 100%;
}
.rule-card {
  margin-bottom: 10px;
  background: #f9fbfd;
  border-radius: 10px;
  padding: 12px 16px 8px 16px;
}
</style>
